package cn.cdzdjd.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import cn.cdzdjd.constant.BrowserConstant;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.TxWeiShiVideoService;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class TxWeiShiVideoServiceImpl implements TxWeiShiVideoService {
	private String baseUrl = "https://q.weishi.qq.com";
	@Override
	public VideoInfoVO getVideoInfo(String locationUrl) {
		//System.out.println(locationUrl);
		try {
			Document doc = Jsoup.connect(locationUrl).ignoreContentType(true).userAgent(BrowserConstant.USER_AGENT_PC)
					.header("Accept", BrowserConstant.ACCEPT).referrer(locationUrl).get();
			Element body = doc.body();
			Element script = body.selectFirst("script");
			String scriptData = script.data();
			int headIndex = StringUtils.ordinalIndexOf(scriptData, "{", 2);
			int tailIndex = StringUtils.lastOrdinalIndexOf(scriptData, "}", 3);
			String jsonStr = scriptData.substring(headIndex, tailIndex + 1);
			//System.out.println(jsonStr);
			JSONObject json = new JSONObject(jsonStr);
			JSONObject feedsList = json.getJSONArray("feedsList").getJSONObject(0);

			String title = feedsList.getString("materialDesc");
			String videoUrl = feedsList.getString("videoUrl").replaceAll("\u002F", "/");
			int head = StringUtils.ordinalIndexOf(videoUrl, "/", 4);
			String path = StringUtils.substring(videoUrl, head);
			String video_url = baseUrl+path;
			//String final_video_url = JsoupUtil.downloadVideoUrl(videoUrl);
			List<String> videolist = new ArrayList<>();
			videolist.add(UrlUtil.setHttps(video_url));
			String posterUrl = feedsList.getString("videoCover").replaceAll("\u002F", "/");
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(posterUrl));
			return new VideoInfoVO(videolist, posterList, title, null);
		} catch (IOException e) {
			e.printStackTrace();
			log.error("jsoup访问异常");
			throw new RenException("访问异常");
		}
	}
}
